package com.ruoyi.common.websocket.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 将 "/portfolio" 作为 HTTP URL 注册为一个端点
        // WebSocket（或 SockJS）客户端需要连接该端点进行 WebSocket 握手
        registry.addEndpoint("/portfolio")
            .setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 将目的地头以 /app 开头的 STOMP 消息路由到 @Controller 类中的 @MessageMapping 方法
        config.setApplicationDestinationPrefixes("/appWs");
        // 使用内置的消息代理进行订阅和广播，并将目的地头以 /topic 或 /queue 开头的消息路由到该代理
        // 尽管网上说/user通道不用注册，但不注册客户端收不到消息
        config.enableSimpleBroker("/topic" ,"/user");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new MyChannelInterceptorChannelInterceptor());
    }

}
